package com.tcl.aota.admin.util;

import com.tcl.aota.common.constants.Constants;
import com.tcl.aota.common.utils.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
import java.util.UUID;

/**
 * @author kelong
 * @date 11/5/14
 */
public class FileStoreUtil {
    static Logger LOG = Logger.getLogger(FileStoreUtil.class);

    public static String basePath;

    static {
        init();
    }

    private static void init() {
        String tempDir = FileStoreUtil.getUploadTempDir();
        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }
        String tmpDir2 = Constants.Common.FAILURE_FILE_DIR;
        File tempDirFile2 = new File(tmpDir2);
        if (!tempDirFile2.exists()) {
            tempDirFile2.mkdirs();
        }
    }

    /**
     * copy apk file to the tmp dir
     *
     * @param file
     * @return
     */
    public static String storeAPk(MultipartFile file) {
        String baseName = FilenameUtils.getBaseName(file.getOriginalFilename());
        String originalFileName = FilenameUtils.getExtension(file.getOriginalFilename());
        String uuid = gerneratedFileRand(baseName, originalFileName);
        String tempDir = FileStoreUtil.getUploadTempDir();
        try {
            FileOutputStream os = new FileOutputStream(tempDir + uuid);
            InputStream is = file.getInputStream();
            IOUtils.copy(file.getInputStream(), os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
        return uuid;
    }


    /**
     * copy apk file to the tmp dir
     *
     * @param file
     * @return
     */
    public static String storeImg(MultipartFile file) {
        String baseName = FilenameUtils.getBaseName(file.getOriginalFilename());
        String originalFileName = FilenameUtils.getExtension(file.getOriginalFilename());
        String uuid = gerneratedFiledUUid(originalFileName);
        String tempDir = FileStoreUtil.getUploadTempDir();
        try {
            FileOutputStream os = new FileOutputStream(tempDir + uuid);
            InputStream is = file.getInputStream();
            IOUtils.copy(file.getInputStream(), os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
        return uuid;
    }


    /**
     * copy file to temp dir
     *
     * @param file
     * @param type
     * @return
     */
    public static String storeFile(File file, String fileName, int type) {
        String baseName = FilenameUtils.getBaseName(fileName);
        String originalFileName = FilenameUtils.getExtension(fileName);
        String processFile = "";
        if (type == 0) {
            processFile = gerneratedFileRand(baseName, originalFileName);
        } else {
            processFile = gerneratedFiledUUid(originalFileName);
        }
        String tempDir = FileStoreUtil.getUploadTempDir();
        try {
            File tempDirFile = new File(tempDir);
            if (!tempDirFile.exists()) {
                tempDirFile.mkdirs();
            }
            File descFile = new File(tempDir + processFile);
            FileCopyUtils.copy(file, descFile);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
        return processFile;
    }

    /**
     * copy file to desc DIR
     *
     * @param file
     */

    public static void copyFile(File file,File descFile) {
        try {
            FileUtils.copyFile(file, descFile);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * apk,apkName+randNum+fileextension
     *
     * @param fileExtension
     * @return
     */
    public static String gerneratedFileRand(String baseName, String fileExtension) {
//        UUID uuid = UUID.randomUUID();
        int randomNum = RandomUtils.nextInt(10000);
        if (StringUtils.isEmpty(fileExtension)) {
            return baseName + "_" + randomNum;
        }
        return baseName + "_" + randomNum + "." + fileExtension;
    }

    /**
     * img,uuid+fileExtension
     *
     * @param fileExtension
     * @return
     */
    public static String gerneratedFiledUUid(String fileExtension) {
        UUID uuid = UUID.randomUUID();
        if (StringUtils.isEmpty(fileExtension)) {
            return uuid.toString();
        }
        return uuid.toString() + "." + fileExtension;
    }



    /**
     * tmp dir
     *
     * @return
     */
    public static String getUploadTempDir() {
        String tempDir = System.getProperty("temp_dir");
        if (tempDir == null) {
            tempDir = System.getProperty("java.io.tmpdir");
        }
        return tempDir + File.separator + "aota-store"
                + File.separator;
    }

    /**
     * 定义存储基本正式目录
     *
     * @return
     */
    public static String getFormalDir(HttpServletRequest request) {
        String path = request.getRealPath("/") + Constants.APK.STORE_TEMP + File.separator;
        File formlFile = new File(path);
        if (!formlFile.exists()) {
            formlFile.mkdirs();
        }
        return path;
    }

    /**
     * 获取system host address
     *
     * @param request
     * @return
     */
    public static String getHostAddress(HttpServletRequest request) {
        if (!StringUtils.isEmpty(basePath)) {
            return basePath;
        }
        String path = request.getContextPath();
        basePath =request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/"+Constants.APK.STORE_TEMP;
        return basePath;
    }

    /**
     * get file by uuid
     *
     * @param uuid
     * @return
     */
    public static File getFileViaUUID(String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            return null;
        }
        String tempDir = FileStoreUtil.getUploadTempDir();
        File uuIdFile = new File(tempDir + uuid);
        if (uuIdFile.exists()) {
            return uuIdFile;
        }
        return null;
    }


    /**
     * read file content
     *
     * @param filePath
     * @return
     */
    public static String read(String filePath) {
        StringBuffer sb = new StringBuffer();

        try (RandomAccessFile file = new RandomAccessFile(filePath, "r"); FileChannel channel = file.getChannel();) {
            ByteBuffer buf = MappedByteBuffer.allocateDirect(512);
            while (channel.read(buf) > 0) {
                buf.flip();
                while (buf.hasRemaining()) {
                    sb.append((char) buf.get());
                }
                buf.clear();
            }
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e1) {
            LOG.error(e1.getMessage(), e1);
        }
        return sb.toString();
    }

}
